﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.ComponentModel.Composition;
using DSCop.Core;

namespace DSCop.CoreRules
{
    [Export(typeof(IDSRule))]
    [ExportMetadata("RuleName", "StableSortRule")]
    public class StableSortRule : IDSRule
    {
        #region IDSRule Members

        public IList<RuleViolation> ValidateJob(XElement job)
        {
            IList<XElement> sortStages = DSCopUtil.GetStagesByType(job, "PxSort");

            IList<RuleViolation> violations = new List<RuleViolation>();
            foreach (XElement stage in sortStages)
            {
                var stageProperties = stage
                    .Descendants("Collection")
                    .Descendants("SubRecord");

                foreach (var property in stageProperties)
                {
                    string propertyName = (from p in property.Elements()
                                           where p.Attribute("Name").Value.ToUpper() == "NAME" &&
                                                p.Name.LocalName.ToUpper() == "PROPERTY"
                                           select p.Value).Single();

                    IEnumerable<string> propertyValues = from p in property.Elements()
                                            where p.Attribute("Name").Value.ToUpper() == "VALUE" &&
                                                p.Name.LocalName.ToUpper() == "PROPERTY"
                                            select p.Value;

                    if (propertyName.ToUpper() == "STABLE" && propertyValues.Count() != 0 &&
                        propertyValues.Single().ToUpper() == "STABLE")
                    {
                        violations.Add(new RuleViolation
                        {
                            JobName = DSCopUtil.GetJobName(job),
                            Message = "Stage \"" + DSCopUtil.GetStageName(stage) + "\" uses stable sort."
                        });
                    }
                }
            }

            return violations;
        }

        #endregion
    }
}
